package com.modular.redis;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * reids中的默认值
     */
    private final String CACHE_DEFAULT_VALUE = "on";
    /**
     * 默认5分钟
     */
    public final Integer FIVE = 5;

    /**
     * 判断redis中的key是否有效
     * @param redisKey
     * @return
     */
    public boolean checkRedisKey(String redisKey){
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        if(StrUtil.isNotEmpty(redisValue) && redisValue.equals(CACHE_DEFAULT_VALUE)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 刷新redis中key
     * @param redisKey
     */
    public void flushRedis(String redisKey){
        flushRedis(redisKey,FIVE,TimeUnit.MINUTES);
    }
    /**
     * 刷新redis中key
     * @param redisKey
     */
    public void flushRedis(String redisKey,Integer timeOut,TimeUnit timeUnit){
        redisTemplate.opsForValue().set(redisKey, CACHE_DEFAULT_VALUE,timeOut, timeUnit);
    }

    /**
     * 删除redis中key
     * @param redisKey
     */
    public void delKey(String redisKey){
        redisTemplate.delete(redisKey);
    }

}
